/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.unitn.science.matr155863_148346_145963.bccastestore.servlet;

import it.unitn.science.matr155863_148346_145963.bccastestore.DBManager;
import it.unitn.science.matr155863_148346_145963.bccastestore.utils.Crypto;
import it.unitn.science.matr155863_148346_145963.bccastestore.utils.MailSender;
import it.unitn.science.matr155863_148346_145963.bccastestore.utils.UserDetailsValidator;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nl.captcha.Captcha;
import org.apache.log4j.Logger;

/**
 *
 * @author berto
 */
@WebServlet(name = "RequestNewPasswordSRV", urlPatterns = {"/serivices/requestNewPassword"})
public class RequestNewPasswordSRV extends HttpServlet {

    private DBManager db=null;
    private static Logger log = Logger.getLogger(RequestNewPasswordSRV.class);
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        try {
          db=(DBManager)super.getServletContext().getAttribute("db_manager");
        }catch(Exception e) {
            log.fatal(e);
            throw new UnavailableException(e.toString());
        }
    }
    
    private boolean isCorrectCaptcha(HttpServletRequest request){
        Captcha captcha = (Captcha) request.getSession().getAttribute(Captcha.NAME);
        String answer = request.getParameter("answer");
        if((captcha!=null)&&(answer!=null)&&(captcha.isCorrect(answer))) {
            //Correct
            return true;
        } else {
            //Incorrect
            return false;
        }
    }
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String includeAddress="/contents/public/requestNewPassword.jsp?error=true";
        try {
            String email=request.getParameter("email");
            if((isCorrectCaptcha(request))
                    &&(UserDetailsValidator.isEmail(email))){
                String username=db.userExist(email);
                if(username!=null){
                    //if captcha correct
                    String password = UUID.randomUUID().toString();
                    password=password.substring(0,10);
                    String crypto=Crypto.crypto(password);
                    db.setNewPasword(username,crypto);
                    String text="We have recived your request of new password.\n"
                            + "We ramind you the login credential:\n"
                            + "username: "+username+"\n"
                            + "password:" +password+"\n"
                            + "Plese change it after your connection at BCCAsteStore.\n"
                            + "Click on the link to go on our site:\n"
                            + "http://localhost:8084/"+request.getContextPath()+"home.jsp";
                    MailSender.sendTextMailWithAutentication("Daghen.De.Pu@gmail.com", "daghen.de.pu", "Daghen.De.Pu@gmail.com", email, "BCCA New password request", text);
                    includeAddress="/contents/public/requestNewPasswordSended.jsp";
                }
            }
        }catch(Exception ex){
            includeAddress="/contents/public/errorPage.jsp";
            request.setAttribute("error_message", ex);
        } finally {            
            RequestDispatcher dispatcher=request.getRequestDispatcher(includeAddress);
            dispatcher.include(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
